-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
38 lines (32 loc) · 1.15 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.Scanner;
public class LongestCommonPrefix {
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
int j = 0;
while (j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j)) {
j++;
}
prefix = prefix.substring(0, j);
}
return prefix;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of strings: ");
int n = scanner.nextInt();
scanner.nextLine(); // Consume the newline
String[] strs = new String[n];
System.out.println("Enter the strings:");
for (int i = 0; i < n; i++) {
strs[i] = scanner.nextLine();
}
String result = longestCommonPrefix(strs);
if (!result.isEmpty()) {
System.out.println("Longest Common Prefix: " + result);
} else {
System.out.println("No common prefix.");
}
}
}